import fetch from '@system.fetch';
import media from '@ohos.multimedia.media';
import http from '@ohos.net.http';
import router from '@system.router';
import prompt from '@system.prompt';
import qs from 'querystring';

var counter = 5; // 倒计时计数用
var timer = null; // 时间计时
var tar=1;  // 这个决定的是当前页面状态，是获取数据前还是获取数据后，默认是1，按钮被按会变成2，数据请求函数会触发成3


export default {
    data: {
        url: 'http://120.46.171.116:80/yali.mp4',
        types:'Kneading',
        status:'ON',
        kneading_id:'8',
        seconds:'5',
        percentage:'100',  // 百分比
        progress: 10,
        winfo:"-",

        nieHe:"-",//捏合次数
        nieHeresult:"-",//捏合结果
        fuDu:"-",//幅度
        pinLv:"-",//频率
        wanQu:"-",
        fengFeng:"-",
//      手指捏合参数
        vals11:0,
        vals12:0,
        vals13:0,
//        手指伸展参数
        vals21:0,
        vals22:0,
        vals23:0,
        vals24:0,
        vals25:0,
        vals26:0,
//        手部震颤参数
        vals31:0,
        vals32:0,
        vals33:0,
//        手臂弯曲参数
        vals41:0,
        vals42:0,
        nowDate:0,
        num: 3,
        //        time:"2022-04-22 10:56:08",
        startText:"开始检测",

        returnContent:'',
        return_result: {
        },
//        文字透明度
        opacity:0,
        z_index:10000,
        visible: false,
//      时间参数
        last_update:String,
        nowtime:String,
        year:Number,
        month:Number,
        date:Number,
        hour:Number,
        minute:Number,
        secondss:Number
    },
//获取当前时间方法
    get_time(){
//定义Date类的对象now
        var now = new Date();
//        获取当前年
        this.year = now.getFullYear()
//        获取当前月，需要加1，与实际月份相差1
        this.month = now.getMonth()+1
//        获取当前日期
        this.date = now.getDate()
//        获取当前小时
        this.hour = now.getHours()
//        获取当前分钟
        this.minute = now.getMinutes()
//        获取当前秒
        this.secondss = now.getSeconds()
//        数字位数小于2时加上0
        if(now.getMonth()+1<10){
            this.month = "0"+ (now.getMonth()+1)
        }
        if(now.getDate()<10){
            this.date = "0"+ now.getDate()
        }
        if(now.getHours()<10){
            this.hour = "0"+ now.getHours()
        }
        if(now.getMinutes()<10){
            this.minute = "0"+ now.getMinutes()
        }
        if(now.getSeconds()<10){
            this.secondss = "0"+ now.getSeconds()
        }
//        制定时间戳
        this.nowtime = this.year.toString() + this.month + this.date + this.hour+ this.minute+this.secondss
//        格式化当前时间
        this.last_update = this.year + "-" + this.month + "-" + this.date + " " + this.hour + ":" +this.minute + ":" + this.secondss
//        打印时间戳和格式化时间
        console.info(this.nowtime)
        console.info(this.last_update)
        console.info("年："+this.year+"月："+this.month+"日："+this.date+"时："+this.hour+"分:"+this.minute+"秒:"+this.secondss)
    },
//显示子当以窗口
    showhintDialog() {
        this.$element('hintDialog').show()
    },

    sethintDialog() {
        this.$element('hintDialog').close()
    },

    tabChange(e){
        console.info("Tab index: " + e.index)
    },
//传输评估信息到主页面
    launch2() {
        router.push ({
            uri: 'pages/home/home',
            params:{
                kneading:this.vals13,
                stretch:this.vals26,
                tremble:this.vals33,
                muscle:this.vals42,
                grade:(this.vals13 + this.vals26 + this.vals33 + this.vals42)/4
            }
        });
    },

    run(types){
        counter--;
        // tar变成2，倒计时5秒
        if (tar==2&&counter!=-1) {
            this.seconds = counter.toString();
            // 倒计时计算的过程会赋值给cat,cat为0倒计时就结束了
            //            cat = counter.toString();
            this.percentage = counter*20;  // 百分比
            if(counter==0){

                this.num=3  // 重新赋值预备3S

                // 按钮变成开始检测
                this.startText="开始检测"
                tar=3;
            }
        } else{  //这个是tar==3时候会触发的
            this.seconds = "0";
            clearInterval(timer);
            timer = null;
            //计时结束会变成0
            //下面这个就是具体的请求数据了，请求的是服务器里传感器的数据

            //            console.info(JSON.stringify({"types":types,"status":status,"kneading_id":this.kneading_id}));
            tar = 1;
            counter = 5;
            this.percentage = 100;

            let that = this;

            prompt.showToast({
                message: "检测成功",
                duration: 3000,
            })

            that.visible = true

            // 延迟2000毫秒执行查询
            setTimeout(()=>{
                that.getData(types)
                that.visible = false
            }, 2000)

        }
    },
    // 重置用的tar会被重置成1，倒计时记录会归0
    remake(){
        tar=1;
        this.startText="开始检测"
        counter = 10;
    },

    get_cd(types, status){
        let httpRequest = http.createHttp();
        // 创建一个http，里面包括发起请求、中断请求、订阅/取消订阅HTTP Response Header 事件。
        let url = "http://120.46.171.116:8082/get_command?types="+types+"&status="+status;
        console.info(url)
        httpRequest.request(url, {
            // 注意请求方法：http.POST
            method: http.POST, // 可选，默认为http.RequestMethod.GET，实际是http.POST这一点与官网不同
            //发送用户account参数和检测时间
            extraData: {
                account:"15565988801",
                time:this.nowtime
            },
        }, (err, data)=> {  // 判断是否请求成功
            if (!err) {  // 请求成功
                console.info(types);
                console.info("命令下发成功")
                // prompt.showToast({
                //     message: "命令下发成功",
                //     duration: 2000,
                // });
                return 1
            } else {  // 请求失败
                // prompt.showToast({
                //     message: "命令下发失败",
                //     duration: 3000,
                // });
                return 0
            }
        })
        return 0
    },
//    let url = "http://120.46.171.116:8081/get_specified_bend_data";
    getData(types){
        if(types=="Kneading") {
            let jsondata;
            let url = "http://120.46.171.116:8082/get_specified_kneading_data";
            let httpRequest = http.createHttp();
            httpRequest.request(
                url,
                {
                    method: http.POST, // 可选，默认为http.RequestMethod.GET，实际是http.POST这一点与官网不同
//                    发送用户account参数和检测时间
                    extraData: {
                        account:"15565988801",
                        time:this.nowtime
                    },
                }, (err, data) => {
                if (!err) {
                    jsondata = JSON.parse(data.result)
                    prompt.showToast({
                        message:"获取成功",
                        duration: 3000,
                    })
                    this.vals11 = this.last_update;
                    this.vals12 = jsondata.results[0].data.Kneading;
                    this.vals13 = jsondata.results[0].data.kneadlevel;
                    console.info("成功-----------"+"data:"+data.result)
                } else {
                    // prompt.showToast({
                    //     message:"获取失败"
                    // })
                    // console.info("失败")
                }
            }
            );

        } else if(types=="Bend"){
            let jsondata;
            let url = "http://120.46.171.116:8082/get_specified_bend_data";
            let httpRequest = http.createHttp();
            httpRequest.request(
                url,
                {
                    method: http.POST, // 可选，默认为http.RequestMethod.GET，实际是http.POST这一点与官网不同
//                    发送用户account参数和检测时间
                    extraData: {
                        account:"15565988801",
                        time:this.nowtime
                    },
                }, (err, data) => {
                if (!err) {
                    jsondata = JSON.parse(data.result)
                    prompt.showToast({
                        message:"获取成功",
                        duration: 3000,
                    })
                    this.vals21 = jsondata.last_update;
                    this.vals22 = jsondata.angle.bend_index_finger;
                    this.vals23 = jsondata.angle.bend_middle_finger;
                    this.vals24 = jsondata.angle.bend_ring_finger;
                    this.vals25 = jsondata.angle.aver_bend_anger;
                    this.vals26 = jsondata.stretchlevel;
                    console.info("成功-----------"+"data:"+data.result)
                } else {
                    prompt.showToast({
                        message:"获取失败"
                    })
                    console.info("失败")
                }
            }
            );

        } else if(types=="Tremor"){
            let jsondata;
            let url = "http://120.46.171.116:8082/accel_gr_detect";
            let httpRequest = http.createHttp();
            httpRequest.request(
                url,
                {
                    method: http.POST, // 可选，默认为http.RequestMethod.GET，实际是http.POST这一点与官网不同
//                    发送用户account参数和检测时间
                    extraData: {
                        account:"15565988801",
                        time:this.nowtime
                    },
                }, (err, data) => {
                if (!err) {
                    jsondata = JSON.parse(data.result)
                    // prompt.showToast({
                    //     message:"获取成功",
                    //     duration: 3000,
                    // })
                    this.vals31 = jsondata.detect_time;
                    this.vals32 = jsondata.confidence.toFixed(4);
                    this.vals33 = jsondata.label;
                    console.info("成功-----------"+"data:"+data.result)
                } else {
                    // prompt.showToast({
                    //     message:"获取失败"
                    // })
                    // console.info("失败")
                }
            }
            );

        } else if(types=="Muscle"){
            let jsondata;
            let url = "http://120.46.171.116:8082/get_specified_muscle_data";
            let httpRequest = http.createHttp();
            httpRequest.request(
                url,
                {
                    method: http.POST, // 可选，默认为http.RequestMethod.GET，实际是http.POST这一点与官网不同
//                    发送用户account参数和检测时间
                    extraData: {
                        account:"15565988801",
                        time:this.nowtime
                    },
                }, (err, data) => {
                if (!err) {
                    jsondata = JSON.parse(data.result)
                    prompt.showToast({
                        message:"获取成功",
                        duration: 3000,
                    })
                    this.vals41 = jsondata.results[0].last_update;
                    this.vals42 = jsondata.results[0].Muscle.muscle;
                    console.info("成功-----------"+"data:"+data.result)
                } else {
                    prompt.showToast({
                        message:"获取失败"
                    })
                    console.info("失败")
                }
            }
            );

        }

    },

    // 设置播放器回调函数
    setCallBack(audioPlayer) {
        audioPlayer.on('dataLoad', () => {              //设置'dataLoad'事件回调，src属性设置成功后，触发此回调
            console.info('audio set source success');
            audioPlayer.play();                           //调用play方法开始播放，触发'play'事件回调
        });
        audioPlayer.on('play', () => {                  //设置'play'事件回调
            console.info('audio play success');
        });
        audioPlayer.on('finish', () => {                //设置'finish'事件回调，播放完成触发
            console.info('audio play finish');
            audioPlayer.release();                        //audioPlayer资源被销毁
            audioPlayer = undefined;
        });
        audioPlayer.on('error', (error) => {             //设置'error'事件回调
            console.info(`audio error called, errName is ${error.name}`);
            console.info(`audio error called, errCode is ${error.code}`);
            console.info(`audio error called, errMessage is ${error.message}`);
        });
    },

    async audioPlayerDemo() {
        let audioPlayer = media.createAudioPlayer();     //创建一个音频播放实例
        this.setCallBack(audioPlayer);                   //设置事件回调
        let fdPath = 'http://120.46.171.116/countdown.mp3'
        audioPlayer.src = fdPath; //设置src属性，并触发'dataLoad'事件回调
    },

    start_detection(types) {
        this.get_time();     //获取当前时间
        var type = types;
        var status = 'ON';
        let that = this;
        that.showhintDialog()
        that.audioPlayerDemo()
        // 等待检测，3S准备时间
        let aa = setInterval(function() {
            that.num--;
            if(that.num==0){
                that.sethintDialog()
                clearInterval(aa)

                prompt.showToast({
                    message: "开始检测",
                    duration: 2000,
                });
                if(tar==1) {
                    that.get_cd(type, status)  // 命令下发，开始检测
                } else if(tar==3) {
                    that.startText="开始检测"
                    tar=1;
                } else{
                    that.startText="重新检测"
                }

                tar=2;
                clearInterval(timer);
                that.seconds = counter.toString();
                timer = setInterval(function(){
                    that.run(type)
                }, 1000);
                that.startText="检测中..."
                return;
            }
           },1000)
    },
}